package com.example.baiduai.utils;

import com.google.gson.*;

import java.lang.reflect.Type;

public class GsonUtils {

    public static Gson gson = getGson();

    public static JsonParser jsonParser = new JsonParser();

    public static GsonBuilder gsonBuild = new GsonBuilder();


    /**
     * GsonBuilder gsonBuilder = new GsonBuilder();
     *         gsonBuilder.registerTypeAdapter(GrantedAuthority.class, new mYGrantedAuthority());
     *         Gson gson = gsonBuilder.create();
     *
     *
     *    对象 参数中  有接口参数的序列化
     */
    public static <T,B> Gson gsonBuilder(Class<T> clazz,B bean){
        gsonBuild.registerTypeAdapter(clazz, bean);
        return gsonBuild.create();
    }


    public static <T> T gsonToBean(Object obj, Class<T> clazz) {
        return gson.fromJson(gson.toJson(obj), clazz);
    }


    private static Gson getGson() {
        if (gson == null) {
            synchronized (GsonUtils.class) {
                if (gson == null) return new Gson();
            }
        }
        return gson;
    }

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T toBean(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }


    /**
     * 需要用集合去接收，解析的时候总是报错，发现用Gson解析的时候没法确定返回数据的类型。所以用到
     * TypeToken去指定返回类型。
     * List<VersionBean> versionList
     * 		String jsonStr = "返回的json数据";
     * 		Gson gson = new Gson();
     *         List<Bean> versionList;
     *         Type type = new TypeToken<ArrayList<Bean>>() {
     *         }.getType();
     *         versionList = gson.fromJson(jsonStr , type);
     * @param json
     * @param typeOfT
     * @param <T>
     * @return
     * @throws JsonParseException
     */
    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }

    /**
     *  判断是不是  json 数组
     * @param json
     * @return
     */
    public static boolean isJsonList(String json){
        try {
            return  jsonParser.parse(json).isJsonArray();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 判断是不是 json 对象
     * @param json
     * @return
     */
    public static boolean isJsonObj(String json){
        try {
            return   jsonParser.parse(json).isJsonObject();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return false;
        }
    }


}
